import Settings from '../config/Settings.js';

export default class Player {
  constructor(game, options = {}) {
    this.game = game;
    
    // 设置玩家初始位置在屏幕中央偏左的位置
    this.x = options.x || game.gameWidth / 3;
    this.y = options.y || game.gameHeight - 200;  // 距离底部200像素
    
    // 使用Settings中的尺寸配置
    this.width = Settings.player.width;
    this.height = Settings.player.height;
    
    this.verticalVelocity = 0;
    this.jumpCount = 0;
    this.onGround = false;
    this.isInvincible = false;
    this.invincibleTimer = 0;
    this.rotation = 0;
    
    this.currentFrame = Settings.spriteConfig.animations.idle.startFrame;
    this.image = game.getImage('rabbit');
    
    // 添加攻击相关属性
    this.isAttacking = false;
    this.attackTimer = 0;
    this.attackDuration = 20; // 攻击持续时间（帧数）
    this.attackCooldown = 0;
    this.attackCooldownTime = 30; // 攻击冷却时间（帧数）
    
    // 添加动画状态
    this.currentAnimation = 'idle';
    this.animationTimer = 0;
    this.facingRight = true; // 朝向
    
    // 添加新属性
    this.damageMultiplier = 1;
    this.jumpForceMultiplier = 1;
    this.speedTrail = false;
    
    // 添加能力状态跟踪
    this.unlockedAbilities = new Set();
    this.maxJumps = Settings.player.maxJumps;
    this.lastCarrotCount = 0;  // 用于检测胡萝卜数量变化
    
    // 添加武器系统
    this.weapons = {
      carrotGun: {
        ammo: Settings.weapons.maxAmmo.carrotGun,
        cooldown: 0
      },
      carrotBomb: {
        ammo: Settings.weapons.maxAmmo.carrotBomb,
        cooldown: 0
      },
      carrotLaser: {
        ammo: Settings.weapons.maxAmmo.carrotLaser,
        cooldown: 0
      }
    };
    
    this.currentWeapon = 'carrotGun';
    this.projectiles = [];
    
    // 移动相关
    this.moveSpeed = 5;
    this.maxSpeed = 8;
    this.horizontalVelocity = 0;
    
    console.log('玩家初始化:', this.x, this.y);
  }
  
  update() {
    try {
      // 获取键盘状态
      const keys = this.game.inputHandler.getKeyState();
      
      // 处理水平移动
      if (keys.left) {
        this.horizontalVelocity = -this.moveSpeed;
        this.facingRight = false;
      } else if (keys.right) {
        this.horizontalVelocity = this.moveSpeed;
        this.facingRight = true;
      } else {
        // 增加缓慢减速而不是立即停止
        this.horizontalVelocity *= 0.8;
        if (Math.abs(this.horizontalVelocity) < 0.1) {
          this.horizontalVelocity = 0;
        }
      }
      
      // 处理垂直移动 - 跳跃
      if (keys.up && this.onGround) {
        this.jump();
      }
      
      // 处理武器攻击
      if (keys.attackA) {
        this.attack('carrotGun');
      }
      if (keys.attackB) {
        this.attack('carrotBomb');
      }
      
      // 更新水平位置
      this.x += this.horizontalVelocity;
      
      // 限制在游戏区域内
      const bounds = this.game.getGameBounds ? this.game.getGameBounds() : { left: 0, right: this.game.gameWidth };
      this.x = Math.max(this.width/2, Math.min(this.x, bounds.right - this.width/2));
      
      // 应用重力 - 只有不在地面上时才应用
      if (!this.onGround) {
        // 获取当前设置
        const isBossFight = this.game.levelManager && this.game.levelManager.currentBoss != null;
        const gravity = isBossFight ? Settings.player.bossMode.gravity : Settings.player.gravity;
        
        // 应用重力，但限制最大下落速度
        if (this.verticalVelocity < 15) { // 最大下落速度
          this.verticalVelocity += gravity;
        }
        
        // 调试信息 - 记录垂直速度
        if (this.game.debugMode && this.game.gameTime % 30 === 0) {
          console.log('垂直速度:', {
            速度: this.verticalVelocity,
            状态: this.onGround ? '地面' : '空中',
            位置Y: this.y
          });
        }
      }
      
      // 注意：垂直位置更新在LevelManager.update中进行
      // 但我们添加安全检查，避免玩家一直下落
      if (this.game && this.game.gameHeight) {
        const bottomLimit = this.game.gameHeight - this.height - 50; // 安全边界
        if (this.y > bottomLimit) {
          // 玩家超出底部边界，重置到地面上
          this.y = bottomLimit;
          this.verticalVelocity = 0;
          this.onGround = true;
          this.jumpCount = 0;
          
          if (this.game.debugMode) {
            console.log('玩家触及底部安全边界，已重置位置');
          }
        }
      }
      
      // 更新动画状态
      this.updateAnimationState();
      
      // 更新无敌状态
      if (this.isInvincible) {
        this.invincibleTimer--;
        if (this.invincibleTimer <= 0) {
          this.isInvincible = false;
        }
      }
      
      // 更新攻击状态
      if (this.isAttacking) {
        this.attackTimer++;
        if (this.attackTimer >= this.attackDuration) {
          this.isAttacking = false;
          this.attackTimer = 0;
        }
      }
      
      // 更新攻击冷却
      if (this.attackCooldown > 0) {
        this.attackCooldown--;
      }
      
      // 检查能力解锁
      this.checkAbilityUnlocks();
      
      // 更新武器冷却
      for (const weapon in this.weapons) {
        if (this.weapons[weapon].cooldown > 0) {
          this.weapons[weapon].cooldown--;
        }
      }
      
      // 更新投射物
      if (typeof this.updateProjectiles === 'function') {
        this.updateProjectiles();
      }
    } catch (error) {
      console.error('Player update error:', error);
      // 重置到安全状态
      this.verticalVelocity = 0;
      this.horizontalVelocity = 0;
    }
  }
  
  // 将动画状态更新提取为单独方法
  updateAnimationState() {
    try {
      const prevAnimation = this.currentAnimation;
      
      if (!this.onGround) {
        // 区分上升和下降的跳跃动画
        if (this.verticalVelocity < 0) {
          // 上升阶段 - 使用jump动画
          this.currentAnimation = 'jump'; 
          
          // 如果垂直速度较大，加快动画速度以强调快速上升感
          const jumpAnim = Settings.spriteConfig.animations.jump;
          if (jumpAnim) {
            jumpAnim.speed = Math.min(0.3, 0.15 + Math.abs(this.verticalVelocity) / 80);
          }
        } else {
          // 下降阶段
          if (Settings.spriteConfig.animations.fall) {
            this.currentAnimation = 'fall';
            
            // 下落速度越快，动画速度越快
            const fallAnim = Settings.spriteConfig.animations.fall;
            if (fallAnim) {
              fallAnim.speed = Math.min(0.3, 0.15 + this.verticalVelocity / 50);
            }
          } else {
            this.currentAnimation = 'jump'; // 使用jump动画作为替代
          }
        }
        
        // 确保玩家始终在空中应用重力
        if (this.verticalVelocity < 15) { // 设置一个终极速度上限来避免过快下落
          this.verticalVelocity += Settings.player.gravity;
        }
      } else if (Math.abs(this.horizontalVelocity) > 0) {
        // 在地面上移动
        this.currentAnimation = 'run';
        
        // 根据移动速度调整动画速度
        const runAnim = Settings.spriteConfig.animations.run;
        if (runAnim) {
          runAnim.speed = Math.min(0.3, 0.15 + Math.abs(this.horizontalVelocity) / 30);
        }
        
        // 如果正在跑动，偶尔添加脚步粒子效果
        if (this.game && this.game.gameTime % 15 === 0 && this.game.particleSystem) {
          this.game.particleSystem.createParticles(
            this.x,
            this.y + this.height/2,
            '#CCCCCC',
            2,
            1,
            2,
            10
          );
        }
      } else {
        // 站立不动
        this.currentAnimation = 'idle';
      }
      
      // 如果动画状态改变，重置计时器和帧
      if (prevAnimation !== this.currentAnimation) {
        this.animationTimer = 0;
        
        // 安全检查：确保动画配置存在
        const animations = Settings.spriteConfig.animations;
        if (animations && animations[this.currentAnimation]) {
          this.currentFrame = animations[this.currentAnimation].startFrame;
        } else {
          // 如果找不到相应的动画配置，回退到idle
          this.currentAnimation = 'idle';
          if (animations && animations.idle) {
            this.currentFrame = animations.idle.startFrame;
          } else {
            // 最后的回退：使用第一帧
            this.currentFrame = 0;
          }
        }
        
        // 记录动画状态变化，便于调试
        console.log('Animation state changed:', {
          from: prevAnimation, 
          to: this.currentAnimation,
          onGround: this.onGround,
          verticalVelocity: this.verticalVelocity,
          position: {x: this.x, y: this.y}
        });
      }
      
      // 更新动画帧
      const animations = Settings.spriteConfig.animations;
      if (animations && animations[this.currentAnimation]) {
        const animation = animations[this.currentAnimation];
        this.animationTimer += animation.speed || 0.1;
        
        if (this.animationTimer >= 1) {
          this.animationTimer -= 1;
          this.currentFrame++;
          if (this.currentFrame > animation.endFrame) {
            this.currentFrame = animation.startFrame;
          }
        }
      }
      
      // 更新旋转角度
      if (!this.onGround) {
        // 在空中时，根据速度调整旋转角度
        this.rotation = this.verticalVelocity * 2;
      } else {
        // 在地面上时，逐渐恢复到0度
        this.rotation = 0;
      }
    } catch (error) {
      console.error('Animation update error:', error);
      // 回退到安全状态
      this.currentAnimation = 'idle';
      this.currentFrame = 0;
    }
  }
  
  render(ctx) {
    try {
      // 保存当前上下文状态
      ctx.save();
      
      // 计算实际绘制位置（考虑缩放和偏移）
      const drawX = this.x - this.width/2;
      const drawY = this.y - this.height/2;
      
      // 绘制调试边框 - 使用不同颜色表示不同状态
      if (this.game && this.game.debugMode) {
        // 根据状态选择不同的颜色
        if (!this.onGround) {
          ctx.strokeStyle = this.verticalVelocity < 0 ? 'blue' : 'yellow'; // 跳跃/下落状态不同颜色
        } else if (Math.abs(this.horizontalVelocity) > 0) {
          ctx.strokeStyle = 'green'; // 移动状态
        } else {
          ctx.strokeStyle = 'red'; // 站立状态
        }
        
        ctx.lineWidth = 2;
        ctx.strokeRect(drawX, drawY, this.width, this.height);
        
        // 绘制底部碰撞点
        ctx.fillStyle = this.onGround ? 'lime' : 'white';
        ctx.beginPath();
        ctx.arc(this.x, this.y + this.height/2, 4, 0, Math.PI * 2);
        ctx.fill();
        
        // 添加状态文本
        ctx.fillStyle = 'white';
        ctx.font = '10px Arial';
        ctx.textAlign = 'center';
        let statusText = this.onGround ? 'GROUND' : (this.verticalVelocity < 0 ? 'JUMP' : 'FALL');
        ctx.fillText(statusText, this.x, this.y - 10);
      }
      
      // 添加一个"触地"光环效果
      if (this.onGround) {
        try {
          ctx.save();
          const gradient = ctx.createRadialGradient(
            this.x, this.y + this.height/2, 0,
            this.x, this.y + this.height/2, this.width/2
          );
          gradient.addColorStop(0, 'rgba(255, 255, 255, 0.3)');
          gradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
          
          ctx.fillStyle = gradient;
          ctx.beginPath();
          
          // 使用矩形作为后备，如果ellipse方法不可用
          if (typeof ctx.ellipse === 'function') {
            ctx.ellipse(
              this.x, 
              this.y + this.height/2, 
              this.width/2, 
              this.height/6, 
              0, 0, Math.PI * 2
            );
          } else {
            // 后备椭圆形状
            ctx.fillRect(
              this.x - this.width/2,
              this.y + this.height/2 - this.height/6,
              this.width,
              this.height/3
            );
          }
          
          ctx.fill();
          ctx.restore();
        } catch (error) {
          console.error('Error drawing ground effect:', error);
        }
      }
      
      // 尝试绘制兔子精灵图
      let drawSuccess = false;
      try {
        const image = this.game && this.game.getImage ? this.game.getImage('rabbit') : null;
        
        if (image && !image.isPlaceholder) {
          // 计算精灵图帧位置
          const spriteConfig = Settings.spriteConfig || {};
          const frameWidth = spriteConfig.frameWidth || 64;
          const frameHeight = spriteConfig.frameHeight || 64;
          const framesPerRow = spriteConfig.framesPerRow || 7;
          
          const frameX = (this.currentFrame % framesPerRow) * frameWidth;
          const frameY = Math.floor(this.currentFrame / framesPerRow) * frameHeight;
          
          // 保存上下文状态
          ctx.save();
          
          // 计算垂直偏移
          let yOffset = 0;
          if (!this.onGround) {
            // 跳跃时略微上移，下落时略微下移
            yOffset = this.verticalVelocity < 0 ? -3 : 3; 
          } else if (this.onGround) {
            // 在地面上的微小弹跳
            yOffset = this.game && this.game.gameTime ? 
              Math.sin(this.game.gameTime * 0.1) * 2 : 0;
          }
          
          // 绘制角色 - 考虑朝向
          if (!this.facingRight) {
            // 水平翻转角色
            ctx.translate(drawX + this.width, drawY + yOffset);
            ctx.scale(-1, 1);
            
            if (!this.onGround) {
              const rotationAngle = this.verticalVelocity < 0 ? -0.05 : 0.05;
              ctx.rotate(rotationAngle);
            }
          } else {
            // 正常绘制
            ctx.translate(drawX, drawY + yOffset);
            
            if (!this.onGround) {
              const rotationAngle = this.verticalVelocity < 0 ? 0.05 : -0.05;
              ctx.rotate(rotationAngle);
            }
          }
          
          // 绘制精灵
          ctx.drawImage(
            image,
            frameX, frameY,
            frameWidth, frameHeight,
            0, 0,
            this.width, this.height
          );
          
          ctx.restore();
          drawSuccess = true;
          
          // 添加粒子效果
          this.addParticleEffects();
        }
      } catch (error) {
        console.error('渲染玩家时发生错误:', error);
      }
      
      // 如果精灵绘制失败，使用备用图形
      if (!drawSuccess) {
        this.drawRabbit(ctx);
      }
      
      // 恢复上下文状态
      ctx.restore();
      
      // 每120帧输出一次渲染信息
      if (this.game && this.game.gameTime && this.game.gameTime % 120 === 0) {
        console.log('玩家渲染信息:', {
          position: { x: this.x, y: this.y },
          size: { width: this.width, height: this.height },
          onGround: this.onGround,
          sprite: {
            currentFrame: this.currentFrame,
            currentAnimation: this.currentAnimation,
            facingRight: this.facingRight
          }
        });
      }
    } catch (error) {
      console.error('Player render critical error:', error);
      
      // 最后的备用绘制 - 只是简单地画一个矩形，确保画面不会完全黑屏
      try {
        ctx.save();
        ctx.fillStyle = 'pink';
        ctx.fillRect(this.x - 32, this.y - 32, 64, 64);
        ctx.restore();
      } catch (e) {
        // 即使这里失败了，也不再尝试恢复，以避免无限错误循环
      }
    }
  }
  
  // 提取粒子效果为单独方法
  addParticleEffects() {
    if (!this.game || !this.game.particleSystem) return;
    
    try {
      // 空中效果
      if (!this.onGround && this.game.gameTime % 5 === 0) {
        const particleColor = this.verticalVelocity < 0 ? '#FFFFFF' : '#DDDDDD';
        const particleCount = Math.abs(this.verticalVelocity) > 5 ? 3 : 1;
        
        this.game.particleSystem.createParticles(
          this.x,
          this.y + this.height/2,
          particleColor,
          particleCount,
          2,
          2,
          10
        );
      }
      
      // 地面效果
      if (this.onGround && Math.abs(this.horizontalVelocity) > 0 && this.game.gameTime % 8 === 0) {
        const particleX = this.x - (this.facingRight ? this.width/3 : -this.width/3);
        
        this.game.particleSystem.createParticles(
          particleX,
          this.y + this.height/2,
          '#BBBBBB',
          2,
          1,
          2,
          8
        );
      }
    } catch (error) {
      console.error('Error creating particle effects:', error);
    }
  }
  
  checkAbilityUnlocks() {
    const currentCarrots = this.game.scoreManager.getCarrots();
    
    // 如果胡萝卜数量没有变化，不需要检查
    if (currentCarrots === this.lastCarrotCount) return;
    this.lastCarrotCount = currentCarrots;
    
    // 检查二段跳解锁条件
    const doubleJumpAbility = Settings.player.abilities.doubleJump;
    if (!this.unlockedAbilities.has('doubleJump') && 
        currentCarrots >= doubleJumpAbility.requiredCarrots) {
      this.unlockAbility('doubleJump');
    }
  }
  
  unlockAbility(abilityName) {
    if (this.unlockedAbilities.has(abilityName)) return;
    
    this.unlockedAbilities.add(abilityName);
    const ability = Settings.player.abilities[abilityName];
    
    switch(abilityName) {
      case 'doubleJump':
        this.maxJumps = 2;
        // 创建解锁提示效果
        this.game.particleSystem.createParticles(
          this.x,
          this.y,
          '#FFD700', // 金色
          20,
          6,
          8,
          40
        );
        
        // 添加解锁提示文本
        if (this.game.floatingTexts) {
          this.game.floatingTexts.push({
            content: `解锁新能力：${ability.name}`,
            x: this.x,
            y: this.y - 50,
            color: '#FFD700',
            alpha: 1,
            velocity: -2
          });
        }
        break;
    }
  }
  
  jump() {
    // 只有在地面上或者还有跳跃次数时才能跳跃
    if (this.onGround || this.jumpCount < this.maxJumps) {
      // 获取正确的跳跃力
      const isBossFight = this.game.levelManager && this.game.levelManager.currentBoss != null;
      const jumpForce = isBossFight ? Settings.player.bossMode.jumpForce : Settings.player.jumpForce;
      
      // 设置垂直速度为负值（向上）
      this.verticalVelocity = jumpForce;
      
      // 如果是二段跳，增加一个特殊效果
      if (!this.onGround) {
        // 二段跳特效
        this.game.particleSystem.createParticles(
          this.x,
          this.y + this.height/2,
          '#87CEEB', // 天蓝色
          10,
          5,
          3,
          15
        );
        
        // 二段跳时增加垂直速度的乘数
        this.verticalVelocity *= Settings.player.jumpMultiplier;
      }
      
      // 更新状态
      this.onGround = false;
      this.jumpCount++;
      
      // 添加跳跃粒子效果
      this.game.particleSystem.createParticles(
        this.x,
        this.y + this.height,
        '#FFFFFF',
        8,
        5,
        4,
        20
      );
      
      // 调试信息
      if (this.game.debugMode) {
        console.log('跳跃:', {
          力度: this.verticalVelocity,
          次数: this.jumpCount,
          位置: {x: this.x, y: this.y}
        });
      }
    }
  }
  
  takeDamage() {
    if (this.isInvincible) return;
    
    console.log('玩家受伤!');
    this.isInvincible = true;
    this.invincibleTimer = 60; // 1秒无敌时间
    
    // 击退效果
    this.verticalVelocity = -10;
  }
  
  // 备用绘制方法
  drawRabbit(ctx) {
    // 绘制一个简单的兔子形状作为备用
    
    // 使用player的x和y位置，不使用translate
    const x = this.x - this.width/2;
    const y = this.y - this.height/2;
    
    // 身体（白色矩形）
    ctx.fillStyle = 'white';
    ctx.fillRect(x, y, this.width, this.height);
    
    // 耳朵（两个小矩形）
    ctx.fillRect(x + this.width/4, y - this.height/4, this.width/6, this.height/4);
    ctx.fillRect(x + this.width*2/3, y - this.height/4, this.width/6, this.height/4);
    
    // 眼睛（两个黑点）
    ctx.fillStyle = 'black';
    ctx.fillRect(x + this.width/3, y + this.height/3, this.width/10, this.height/10);
    ctx.fillRect(x + this.width*2/3, y + this.height/3, this.width/10, this.height/10);
    
    // 鼻子（粉色小三角）
    ctx.fillStyle = 'pink';
    ctx.beginPath();
    ctx.moveTo(x + this.width/2, y + this.height/2);
    ctx.lineTo(x + this.width/2 - this.width/10, y + this.height/2 + this.height/10);
    ctx.lineTo(x + this.width/2 + this.width/10, y + this.height/2 + this.height/10);
    ctx.closePath();
    ctx.fill();
  }
  
  reset() {
    // 使用游戏设计尺寸来计算位置
    this.x = this.game.gameWidth / 3;
    this.y = this.game.gameHeight - 200;  // 距离底部200像素
    this.verticalVelocity = 0;
    this.jumpCount = 0;
    this.onGround = false;
    this.isInvincible = false;
    this.invincibleTimer = 0;
    this.rotation = 0;
    this.currentFrame = Settings.spriteConfig.animations.idle.startFrame;
  }
  
  attack(weaponType) {
    const weapon = this.weapons[weaponType];
    const weaponConfig = Settings.weapons.types[weaponType];
    
    if (weapon.ammo > 0 && weapon.cooldown <= 0) {
      // 创建投射物
      const projectile = {
        x: this.x + this.width/2,
        y: this.y + this.height/2,
        type: weaponType,
        speed: weaponConfig.speed,
        size: weaponConfig.size,
        damage: weaponConfig.damage,
        color: weaponConfig.color
      };
      
      this.projectiles.push(projectile);
      
      // 更新弹药和冷却
      weapon.ammo--;
      weapon.cooldown = weaponConfig.cooldown;
      
      // 创建发射特效
      this.game.particleSystem.createParticles(
        projectile.x,
        projectile.y,
        weaponConfig.color,
        5,
        3,
        4,
        20
      );
    }
  }
  
  updateProjectiles() {
    for (let i = this.projectiles.length - 1; i >= 0; i--) {
      const projectile = this.projectiles[i];
      const weaponConfig = Settings.weapons.types[projectile.type];
      
      // 移动投射物
      projectile.x += projectile.speed;
      
      // 检查是否离开屏幕
      if (projectile.x > this.game.canvas.width) {
        this.projectiles.splice(i, 1);
        continue;
      }
      
      // 检查与敌人的碰撞
      this.checkProjectileCollisions(projectile);
    }
  }
  
  checkProjectileCollisions(projectile) {
    // 检查与敌人的碰撞
    for (const enemy of this.game.levelManager.enemies) {
      if (this.checkCollision(projectile, enemy)) {
        const weaponConfig = Settings.weapons.types[projectile.type];
        
        // 处理不同类型的武器效果
        switch(projectile.type) {
          case 'carrotBomb':
            // 创建爆炸效果
            this.createExplosion(projectile.x, projectile.y, weaponConfig.explosionRadius);
            break;
          case 'carrotLaser':
            // 创建激光效果
            this.createLaserEffect(projectile.x, projectile.y);
            break;
        }
        
        // 造成伤害
        enemy.takeDamage(projectile.damage);
        
        // 移除投射物
        const index = this.projectiles.indexOf(projectile);
        if (index > -1) {
          this.projectiles.splice(index, 1);
        }
      }
    }
  }
  
  createExplosion(x, y, radius) {
    // 创建爆炸粒子效果
    this.game.particleSystem.createParticles(
      x,
      y,
      '#FF4500',
      20,
      8,
      6,
      40
    );
    
    // 检查范围内的敌人
    for (const enemy of this.game.levelManager.enemies) {
      const distance = Math.sqrt(
        Math.pow(enemy.x - x, 2) + 
        Math.pow(enemy.y - y, 2)
      );
      
      if (distance < radius) {
        enemy.takeDamage(20);
      }
    }
  }
  
  createLaserEffect(x, y) {
    // 创建激光特效
    this.game.particleSystem.createParticles(
      x,
      y,
      '#FFD700',
      10,
      4,
      3,
      15
    );
  }
  
  // 添加移动方法
  move(direction) {
    this.moveDirection = direction;
  }
  
  // 停止移动
  stopMove() {
    this.moveDirection = 0;
  }
} 